// connect.js
// 获取应用实例
var app = getApp();
var self;
var mqtt = require('../../js/mqtt.js');

var timer;
var topic_type = 0;
var is_checked = false;
var resp_topic;

Page({
	data: {
		img_master: '/res/led_on.bmp',
		img_slave: "/res/led_off.bmp",
        led_master: "开",
        led_slave: "关",
		th: 25,
		rh: 65,
		lux: 250,
		topic: '',
		payload: '',
		log: '',
        is_report: false,
        is_control: false,
        report_time: 5000,
	},
	onLoad: function (options) {
		console.log("on load");
		var self = this;
		self.setData({
			topic: '$oc/devices/' + app.globalData.device_id + '/sys/properties/report',
			payload: '{"services":[{"properties":{"LUX":20,"TH":18,"RH":77},"service_id":"SENSOR"}]}'
		});
	},
	get_timer: function (e) {
		this.setData({
            report_time: e.detail.value,
        });
	},
	//上报属性函数
	reportData: function (e) {
		self = this;
        self.setData({
            is_report: e.detail.value
        });
		const client = app.globalData.client;
		if (client == null || client.connected == false) {
			console.log('device is not connect to platform');
			return;
		}
        console.log(self.data.is_report);
		if (self.data.is_report) {
			timer = setInterval(() => {
				console.log('topic:' + self.data.topic);
                //获取随机数，模拟设备
                self.setData({
                    th: self.rand_int(10, 40),
                    rh: self.rand_int(20,80),
                    lux: self.rand_int(0,500)
                });
                //设置mqtt负载数据
                self.setData({
                    payload: '{"services":[{"properties":{"LUX":' + self.data.lux + ',"TH":' + self.data.th + ',"RH":'+ self.data.rh +'},"service_id":"SENSOR"}]}'
                });
                //发布数据
				client.publish(self.data.topic, self.data.payload);
				console.log('publish message successful');
			}, self.data.report_time);
		} else {
			clearInterval(timer);
			//client.publish(self.data.topic, self.data.payload);
			//console.log('publish message successful');
		}
	},
	//订阅主题
	subscribe: function (e) {
		self = this;
        self.setData({
            is_control: e.detail.value,
        })
        console.log(self.data.is_control);
        if (self.data.is_control){
		const client = app.globalData.client;
		console.log(app.globalData.device_id);
		if (client == null || client.connected == false) {
			console.log('device is not connect to platform');
			return;
		}
		//设置要订阅的主题
		var topic = [
			'$oc/devices/' + app.globalData.device_id + '/sys/commands/#',
			'$oc/devices/' + app.globalData.device_id + '/sys/properties/get/#'
		]
		//开始订阅
		for (var i in topic) {
			console.log('subscribe topic:' + topic[i]);
			//订阅主题
			client.subscribe(topic[i], { qos: 1 }, function (err, granted) {
				if (!err) {
					console.log('subscribe message successful');
				}
			});
		}
		//消息处理
		client.on('message', (topic, message, packet) => {
			console.log('receive message topic:' + topic);
			console.log('receive message content:' + message.toString());    
            //得到应答主题
            resp_topic = getResponseTopic(topic);
            //响应控制
            if(topic_type == 0){
                //将字符串转为JSON格式
                var rec_content = JSON.parse(message.toString());
                //控制设备
                ctl_device(rec_content);
            }
			//收到命令下发请求时，返回命令的响应，用=将request_id提出
            sendResponse(resp_topic);
		});

        function ctl_device(param){
            var service_id = param.service_id;
            var cmd_name = param.command_name;
            var cmd_value = param.paras.STATE_CTL;
            if(cmd_name == "LED1_CTL"){
                if(cmd_value == "ON"){
                    self.setData({
                        img_master: '/res/led_on.bmp',
                        led_master: "开"
                    })
                }else{
                    self.setData({
                        img_master: '/res/led_off.bmp',
                        led_master: "关"
                    })                   
                }
            }else if(cmd_name == "LED2_CTL"){
                if (cmd_value == "ON") {
                    self.setData({
                        img_slave: '/res/led_on.bmp',
                        led_slave: "开"
                    })
                } else {
                    self.setData({
                        img_slave: '/res/led_off.bmp',
                        led_slave: "关"
                    })
                }
            }
        }
		//发送应答
		function sendResponse(topic) {
			console.log('response topic is ' + resp_topic);
			//应答数据
			var responseReqJson = {
				result_code: 0,
				response_name: 'COMMAND_RESPONSE',
				paras: { result: 'success' }
			};
			//不同的主题，应答不一样
			if (topic_type == 1) {
				responseReqJson = {
					services: [
						{
							service_id: "SENSOR",
							properties: {
								LUX: self.data.lux,
								TH: self.data.th,
								RH: self.data.rh
							}
						}
					]
				};
			} else if (topic_type == 2) {
				responseReqJson = {
					result_code: 0,
					response_name: 'COMMAND_RESPONSE',
					paras: { result: 'success' }
				};
			}
			let responseReq = JSON.stringify(responseReqJson);
			console.log('response message is ' + responseReq);
			client.publish(resp_topic, responseReq);
		}

		//获取应答主题，此处要参考官方的MQTT手册
		function getResponseTopic(topic) {
			var request_id = topic.split("=")[1];
			//命令下发应答主题
			if (topic.split("/")[4] == "commands") {
				topic_type = 0;
				return (
					'$oc/devices/' +
					app.globalData.device_id +
					'/sys/commands/response/request_id=' +
					request_id
				);
			} else if (topic.split("/")[4] == "properties") {
				//平台查询设备属性 应答主题
				if (topic.split("/")[5] == "get") {
					topic_type = 1;
					console.log("change topic " + topic_type);
					return (
						'$oc/devices/' +
						app.globalData.device_id +
						'/sys/properties/get/response/request_id=' +
						request_id
					);
				}
				//平台设置属性 应答主题
				else {
					topic_type = 2;
					return (
						'$oc/devices/' +
						app.globalData.device_id +
						'/sys/properties/set/response/request_id=' +
						request_id
					);
				}
			}
		}

		function log(msg) {
			console.log(new Date() + ' - ' + msg
			);
			self.data.log = self.data.log + new Date() + ' - ' + msg + '\r\n';
			self.setData({
				log: self.data.log
			})
		}
        }
	},

    rand_int:function(f, t){
        return Math.round(Math.random()*(t-f)+f);
    }
})
